//
//  BLLocalize.m
//  Benz.L
//
//  Created by Benz.L on 23/08/2018.
//  Copyright © 2018 BENZL. All rights reserved.
//

#import "BLLocalize.h"

BLLocalizeLanguage const BLLocalizeLanguageEnglish = @"en";
BLLocalizeLanguage const BLLocalizeLanguageChineseHans = @"zh-Hans";
BLLocalizeLanguage const BLLocalizeLanguageChineseHant = @"zh-Hant";

@interface BLLocalize() {
}
@property(nonatomic, strong) NSString *lprojPath;
@end
@implementation BLLocalize

+ (instancetype)localize {
    static BLLocalize *localize = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        localize = [[BLLocalize alloc] init];
    });
    return localize;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        self.language = self.defaultLanguage;
    }
    return self;
}

- (NSString *)localizedStringForKey:(NSString *)key {
    NSString *result = [[NSBundle bundleWithPath:self.lprojPath] localizedStringForKey:key value:nil table:nil];
    return result?:key;
}

- (void)setLanguage:(BLLocalizeLanguage)language {
    if (!_language || ![language isEqual:_language]) {
        _language = language;
        self.lprojPath = [[NSBundle mainBundle] pathForResource:_language ofType:@"lproj"];
    }
}

- (BLLocalizeLanguage)defaultLanguage {
    NSString *lan = (NSString *)NSLocale.preferredLanguages.firstObject;
    if ([lan rangeOfString:BLLocalizeLanguageChineseHans].length) {
        return BLLocalizeLanguageChineseHans;
    }
    else if ([lan rangeOfString:BLLocalizeLanguageChineseHant].length) {
        return BLLocalizeLanguageChineseHant;
    }
    else {
        return lan;
    }
}
@end
